package zcj.stu;

import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.web.context.WebApplicationContext;

import org.springframework.web.method.HandlerMethod;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Map;
@Slf4j
public class C20 {
    public static void main(String[] args) throws Exception {
        //支持java配置类、内嵌web容器创建spring容器
        WebApplicationContext context=new
                AnnotationConfigServletWebServerApplicationContext(WebConfig.class);
        RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);
        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
        handlerMethods.forEach((requestMappingInfo, handlerMethod) -> {
            System.out.print(requestMappingInfo+":");
            System.out.println(handlerMethod);
        });
        MockHttpServletRequest request = new MockHttpServletRequest("POST", "/c/i");
        request.addHeader("token","HUIGUIGUIGUI");
        HandlerExecutionChain chain = mapping.getHandler(request);
        System.out.println(chain);
        RequestMappingHandlerAdapter adapter = context.getBean(RequestMappingHandlerAdapter.class);
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        for (HandlerMethodArgumentResolver argumentResolver : adapter.getArgumentResolvers()) {
            System.out.println(argumentResolver);
        }
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        for (HandlerMethodReturnValueHandler returnValueHandler : adapter.getReturnValueHandlers()) {
            System.out.println(returnValueHandler);
        }
        log.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        //利用反射调用私有方法
        MockHttpServletResponse response = new MockHttpServletResponse();
        Method invokeHandlerMethod = adapter.getClass().getDeclaredMethod("invokeHandlerMethod", HttpServletRequest.class, HttpServletResponse.class,HandlerMethod.class);
        invokeHandlerMethod.setAccessible(true);
        invokeHandlerMethod.invoke
                (adapter,new Object[]{request,response,chain.getHandler()});
        String contentAsString = response.getContentAsString();
        log.warn(contentAsString);
    }
}
